/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { InputStream } from './InputStream'
import fs from '@ohos.file.fs';
import hilog from '@ohos.hilog';

export class HexInputStream extends InputStream {
  private LINE_LENGTH: number = 128;

  private localBuf: Uint8Array;
  private localPos: number;
  private pos: number;
  private size: number;
  private lastAddress: number;
  private bytesRead: number;
  private MBRSize: number;
  private inFs: fs.File;

  constructor(fsHandle: fs.File, mbrSize: number) {
    super(new Uint8Array());
    this.TAG = 'HexInputStream';
    this.localBuf = new Uint8Array[this.LINE_LENGTH];
    this.localPos = this.LINE_LENGTH; // we are at the end of the local buffer, new one must be obtained
    this.size = this.localBuf.length;
    this.lastAddress = 0;
    this.MBRSize = mbrSize;
    this.inFs = fsHandle;

    // this.available = this.calculateBinSize(mbrSize);
  }

  private checkComma(comma: number) {
    let colon: string = ':';
    if (comma != colon.charCodeAt(0)) {
      hilog.error(this.DOMAIN, this.TAG, "Not a HEX file");
    }
  }
  private calculateBinSize(mbrSize: number): number {
    let binSize: number = 0;
    // final InputStream in = this.in;
    // in.mark(in.available());

    let b, lineSize, offset, type: number = 0;
    let lastBaseAddress: number = 0; // last Base Address, default 0
    let lastAddress: number = 0;

    try {
      //TODO: read HEX File
      let fstat = fs.statSync(this.inFs.fd);
      let buf: Uint8Array = new Uint8Array(fstat.size);
      let readCnt: number = fs.readSync(this.inFs.fd, buf);

    } catch (e) {
      hilog.error(this.DOMAIN, this.TAG, `calculateBinSize err: ${JSON.stringify(e)}`)
    }
    return 0;
  }
}